package com.mtsmda.jpa.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import com.mtsmda.jpa.dao.CarDAOI;
import com.mtsmda.jpa.domain.Car;

public class CarDAO implements CarDAOI {

	public EntityManager entityManager = Persistence
			.createEntityManagerFactory("MTSMDA").createEntityManager();

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@Override
	public boolean addCar(Car car) {
		try {
			entityManager.getTransaction().begin();
			Car merge = entityManager.merge(car);
			if (merge == null) {
				throw new SQLException("Not add to database!");
			}
			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean updateCar(Car car) {
		return addCar(car);
	}

	@Override
	public boolean deleteCar(Car car) {
		try {
			entityManager.getTransaction().begin();
			entityManager.remove(car);
			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public Car getCarById(Integer idCar) {
		try {
			Car findCar = entityManager.find(Car.class, idCar);
			if (findCar == null) {
				throw new SQLException("Not found in database!");
			}
			return findCar;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List<Car> getAllCars() {
		try {
			TypedQuery<Car> createNamedQuery = entityManager.createNamedQuery(
					"Car.getAll", Car.class);

			return createNamedQuery.getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public boolean deleteAllCars() {
		try {
			entityManager.getTransaction().begin();
			Query createNamedQuery = entityManager
					.createNamedQuery("Car.deleteAll");
			createNamedQuery.executeUpdate();
			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean truncateCars() {
		/*
		 * try { entityManager.getTransaction().begin(); Query createNamedQuery
		 * = entityManager .createNamedQuery("Car.truncate");
		 * createNamedQuery.executeUpdate();
		 * entityManager.getTransaction().commit(); return true; } catch
		 * (Exception e) {
		 */return false;
		// }
	}

}